<?php
/**
 * 
 * @author HelloWorld
 * 2014-9-29
 * UTF-8
 */
class Lib_Redis_Base{
	
	protected static $_redis = null;
	protected static $prefix = '';

	/**
	 * 初始化redis对象
	 */
	protected static function _init() {
		if (is_null ( self::$_redis ) || ! isset ( self::$_redis )) {
			$env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
			$env = empty($env)?'local':$env;

            $redisConfig = require LIBRARY_DIR.'/Conf/' . $env . '/redis.php';
			
			if(empty($redisConfig)){
				throw new Exception('can not found the redis_config env:'.$env);
			}
			try {
				self::$_redis = new Redis();
				self::$prefix = empty($redisConfig['prefix']) ? '' : $redisConfig['prefix'];
				self::$_redis->connect($redisConfig['host'], $redisConfig['port']);
				if(isset($redisConfig['auth'])&&!empty($redisConfig['auth'])){
					self::$_redis->auth($redisConfig['auth']);
				}
			} catch ( Exception $e ) {
                Func_Log::write('systion_redis', 'connection',$e->getMessage());
			}
		}
	}
	
	/**
	 * key存活到一个unix时间戳时间
	 * @param unknown_type $key
	 * @param unknown_type $time
	 */
	public static function expireAt($key, $time) {
		self::_init();
		self::$_redis->expireAt(self::$prefix.$key, $time);
	}
	
	/**
	 * 设定一个key的活动时间（s）
	 * @param unknown_type $key
	 * @param unknown_type $expire
	 */
	public static function expire($key, $expire) {
		self::_init();
		self::$_redis->expire(self::$prefix.$key, $expire);
	}
	/**
	 * 切换REDIS
	 * @param $no 切换到的库
	 */
	public static function select($no) {
		self::_init();
		self::$_redis->select($no);
	}
	/**
	 * 删除一个KEY
	 * @param unknown $key
	 * @return number
	 */
	public static function delKey($key){
		self::_init();
		return self::$_redis->delete(self::$prefix.$key);
	}
	
	/**
	 * 判断一个key是否存在
	 * @param unknown $key
	 * @return number
	 */
	public static function exists($key){
		self::_init();
		return self::$_redis->exists(self::$prefix.$key);
	}
	
	/**
	 * 删除$key
	 * @param unknown $key
	 * @return number
	 */
	public static function del($key){
	    self::_init();
	    return self::$_redis->del(self::$prefix.$key);
	}

    /**
     * 以秒为单位,返回给定key的剩余生存时间
     * @param $key
     * @return mixed
     * @throws Exception
     */
    public static function ttl($key){
        self::_init();
        return self::$_redis->ttl( self::$prefix.$key);
    }

}